<template>
	<view class="container" id="content">
		<view class="header">
			<view class="uni-h2 navTitle">个人隐私载体销毁报告</view>
		</view>
		<view class="btn-box " id="dpfbtn">
			<view class="">
				<button size="mini" class="download-btn" @click="getPdf()">下载PDF</button>
			</view>
			
		</view>
		<view class="">
			<view class="uni-h5 title">
				一、个人隐私载体销毁总则
			</view>
			<rich-text :nodes="rule"></rich-text>
			<view class="uni-h5 title">
				二、	个人隐私载体销毁基本信息
			</view>
			<view class="">
				<view class="">
					个人隐私销毁委托人：
				</view>
				本次销毁服务于<text class="blode">{{date}}</text>进行，地点位于<text class="blode">[{{location}}]</text>。
			</view>
			<view class="uni-h5 title">
				三、个人隐私载体销毁载体类型、数量
			</view>
			<view class="" style="margin-bottom: 10px;">
				本次销毁的对象为存储介质，包括但不限于U盘、移动硬盘、电脑硬盘等，数量为{{getItemNum}}个，涉密等级为个人隐私。其中，存储介质中的个人隐私及相关数据信息已由销毁委托人承诺，确保不会对国家安全和利益造成威胁。
			</view>
			<view class="">
				
				<uni-table stripe border emptyText="暂无更多数据">
					<uni-tr>
						<uni-th align="center" width="20">序号</uni-th>
						<uni-th align="center" width="100">介质类型</uni-th>
						<uni-th align="center" width="100">销毁数量</uni-th>
						<uni-th align="center" width="100">销毁时间</uni-th>
						<uni-th align="center" width="100">销毁位置</uni-th>
						<uni-th align="center" width="100">机器编号</uni-th>
						<uni-th align="center" width="100">备注</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in reportData.items">
						<uni-td align="center">{{index+1}}</uni-td>
						<uni-td align="center">{{item.name}}</uni-td>
						<uni-td align="center">1</uni-td>
						<uni-td align="center">{{showRTime(item.update.updateTime)}}</uni-td>
						<uni-td align="center">{{location}}</uni-td>
						<uni-td align="center">{{machineNo}}</uni-td>
						<uni-td align="center">{{item.desc}}</uni-td>
					</uni-tr>
				</uni-table>
			</view>
			<view class="uni-h5 title">
				四、个人隐私载体销毁方式及流程
			</view>
			<view class="">
				<rich-text :nodes="flowPath"></rich-text>
			</view>
			<view class="uni-h5 title">
				五、个人隐私载体销毁效果评价
			</view>
			<view class="">
				<rich-text :nodes="evaluate"></rich-text>
			</view>
			<view class="uni-h5 title">
				六、相关销毁见证信息
			</view>
			<view class="" >
				本次销毁行为的相关见证信息如下:
				<uni-table stripe border>
					
					<uni-tr>
						<uni-td rowspan="2" align="center">设备信息</uni-td>
						<uni-td>机器编号</uni-td>
						<uni-td colspan="2">{{machineNo}}</uni-td>
					</uni-tr>
					<uni-tr>
						<uni-td>销毁位置</uni-td>
						<uni-td colspan="2">{{location}}</uni-td>
					</uni-tr>
					<block v-for="(item,index) in reportData.items">
						
						<uni-tr>
							<uni-td colspan="4" align="center">{{item.name}}见证信息</uni-td>
						</uni-tr>
						<uni-tr>
							<uni-td align="center">介质销毁信息</uni-td>
							<uni-td align="center">投放过程</uni-td>
							<uni-td align="center">销毁过程</uni-td>
							<uni-td align="center">销毁完成</uni-td>
						</uni-tr>
						<uni-tr>
							<uni-td align="center">类型:<br>{{item.name}}</uni-td>
							<uni-td align="center" rowspan="2"><img :src="item.placePic" @click="previewImage(item,0)" lazy-load="true" mode="aspectFit" width="120" height="90"  alt="投放过程"></uni-td>
							<uni-td align="center" rowspan="2"><img :src="item.destoryPic" @click="previewImage(item,1)" mode="aspectFit" width="120" height="90"  alt="销毁过程"></uni-td>
							<uni-td align="center" rowspan="2"><img :src="item.finishPic" @click="previewImage(item,2)"  mode="aspectFit" width="120" height="90" alt="销毁完成"></uni-td>
						</uni-tr>
						<uni-tr>
							<uni-td align="center">时间:<br>{{showRTime(item.update.updateTime)}}</uni-td>
						</uni-tr>
						<uni-tr>
							<uni-td align="center">任务编号:<br>{{businessNo}}_{{item.id}}</uni-td>
							<uni-td align="center">
								<view class="placebtn" >
									<button  :disabled="item.placeVideo===''" size="mini" type="primary" @click="playVideo(index,'place')">播放视频</button>
								</view>
								
								</uni-td>
							<uni-td align="center">
								<view class="destorybtn" >
									<button  :disabled="item.destoryVideo===''" size="mini" type="primary" @click="playVideo(index,'destory')">播放视频</button>
								</view>
								</uni-td>
							<uni-td align="center">
								<view class="finishbtn" >
									<button  :disabled="item.finishVideo===''" size="mini" type="primary" @click="playVideo(index,'finish')">播放视频</button>
								</view>
								</uni-td>
						</uni-tr>
					</block>
					
				</uni-table>
			</view>
			<view class="uni-h5 title">
				七、个人隐私载体销毁总结与展望
			</view>
			<view class="">
				<rich-text :nodes="summarize"></rich-text>
			</view>
			<view class="companyInfo">
				<view class="">
					德佩信息科技集团（黄山）有限公司
				</view>
				<view class="">
					{{date}}
				</view>
			</view>
		</view>
		<uni-popup ref="popup" type="bottom" background-color="rgba(0,0,0,0)">
			<view class="video-box">
				<view class="close-btn">
					<uni-icons type="closeempty" size="30" color="#fff" @click="closwVideo()"></uni-icons>
				</view>
				<video  controls class="video"  :autoplay="videoConfig.autoplay" id="player" ref="player" poster="@/static/loading.gif" :show-center-play-btn="false"></video>
			</view>
		</uni-popup>
		
		
	</view>
</template>

<script>
	import html2Canvas from 'html2canvas'
	import { jsPDF } from 'jspdf'
	import { getReport, getImg, getVideo} from "../../api/index.js"
	import moment from 'moment'
	import config from "@/api/request/config.js"
	import JMuxer from 'jmuxer'
 	export default {
		data() {
			return {
				rule:'<p>1、根据《中华人民共和国个人信息保护法》规定，任何组织、个人不得非法收集、使用、加工、传输他人个人信息，不得非法买卖、提供或者公开他人个人信息。</p>\n\t<p>2、根据《中华人民共和国网络安全法》规定，任何个人和组织不得违反法律法规和商业伦理，采取技术手段或其他手段，未经合法授权，对他人个人信息进行访问、收集、公开或传播。</p>\n\t<p>根据《中华人民共和国刑法》规定，非法获取或泄露他人个人信息，情节严重的，依法追究刑事责任。</p>\n\t<p>3、根据《中华人民共和国民法典》定，任何组织或个人不得以刺探、侵扰、泄露、公开等方式侵害他人的隐私权。</p>\n\t<p>4、根据《中华人民共和国电子商务法》规定，电子商务经营者应当保护用户个人信息，禁止非法收集、使用、加工、传输他人个人信息。</p>\n\t<p>5、根据《中华人民共和国未成年人保护法》规定，任何组织或个人不得披露未成年人的个人隐私，学校和家庭应保护未成年人个人信息。</p>\n\t<p>6、根据《中华人民共和国居民身份证法》规定，任何组织或个人不得非法收集、使用、加工、传输他人居民身份证信息。</p>\n\t',
				evaluate:'经过本次销毁行为，存储介质中的数据已经完全无法恢复，且载体已经完全破坏，不会对个人隐私和对应的数据信息造成任何泄露，感谢您使用销毁卫士个人信息安全平台的销毁服务，让我们一起努力，保护好自己的个人隐私，加强全民信息安全的保护意识。',
				flowPath:'<p>本次销毁采用物理销毁的方式，具体流程如下：</p>\n\t<p>1. 存储介质逐一进行破坏性处理，确保无法再恢复数据；</p>\n\t<p>2. 破坏后的存储介质进行分类整理，统一收集；</p>\n\t<p>3. 销毁后的存储介质已经完全改变其物理或逻辑状态。</p>\n\t',
				summarize:'<p>在信息化、数字化的今天，我们的生活与数字世界交织得越来越紧密。然而，这也意味着我们的个人隐私越来越容易受到侵犯。提高个人隐私安全认知，保护好自己的数字身份，已经成为我们每个人都无法忽视的问题。保护个人隐私是我们每个人的责任，只有提高个人隐私保护意识，才能有效地防止个人隐私被泄露。让我们从现在开始，做好个人隐私保护工作，共同维护一个安全、健康的数字世界。</p>\n\t<p>再次感谢您使用销毁卫士个人信息安全平台的销毁服务！</p>',
				date:new Date,
				location:"九龙工业园",
				machineNo:"",
				businessNo:"",
				reportData:{
					orderNo:"",
					items:[]
				},
				id:0,
				videoConfig:{
					path:'',
					autoplay:false,
				},
				createPdf:false, 
				jmuxer: null,
				videoFile:''
			}
		},
		onLoad({orderId}) {
			this.id=orderId
			this.getData(),
			this.getFullDate(this.date)
		},
		computed:{
			getItemNum(){
				let itemsNum=this.reportData.items.length
				return itemsNum
			}
		},
		methods: {
			//生成PDF
			getPdf(){
				this.createPdf = true
				let that = this
				let shareContent = document.getElementById('content');
				let dpfbtn = document.getElementById('dpfbtn');
				const placeBtn = document.getElementsByClassName('placebtn');
				const destoryBtn = document.getElementsByClassName('destorybtn');
				const finishBtn = document.getElementsByClassName('finishbtn');
				shareContent.style.width="170mm"
				dpfbtn.style.display="none";
				Array.from(placeBtn).forEach(btn => {
					btn.style.display = "none";
				})
				Array.from(destoryBtn).forEach(btn => {
					btn.style.display = "none";
				})
				Array.from(finishBtn).forEach(btn => {
					btn.style.display = "none";
				})
				html2Canvas(shareContent , {
					dpi: 900,
					scrolly: 0,
					// width:eleW,//生成后的宽度
					// height:eleH,//生成后的高度
					scrollx: -10,
					useCORS: true, //允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
	
					// backgroundColor: null //避免图片有白色边框
				}).then((canvas) => {
					shareContent.style.width="auto";
					dpfbtn.style.display="block";
					Array.from(placeBtn).forEach(btn => {
						btn.style.display = "block";
					})
					Array.from(destoryBtn).forEach(btn => {
						btn.style.display = "block";
					})
					Array.from(finishBtn).forEach(btn => {
						btn.style.display = "block";
					})
					let pdf = new jsPDF("p", "mm", "a4") // A4纸，纵向
					let context = canvas.getContext('2d');
					context.mozImageSmoothingEnabled = false;
					context.webkitImageSmoothingEnabled = false;
					context.msImageSmoothingEnabled = false;
					context.imageSmoothingEnabled = false;
					let a4w = 190
					let a4h = 257 // A4大小，210mm x 297mm，四边各保留20mm的边距，显示区域170x25
					let imgHeight = Math.floor(a4h * canvas.width / a4w)
					let pageData = canvas.toDataURL('image/jpeg', 1.0);
					let img = new Image();
					img.src = pageData;
					
					let renderedHeight = 0
					while (renderedHeight < canvas.height) {
					  var page = document.createElement("canvas")
					  page.width = canvas.width
					  page.height = Math.min(imgHeight, canvas.height - renderedHeight)// 可能内容不足一页
			 
					  // 用getImageData剪裁指定区域，并画到前面创建的canvas对象中
					  page.getContext("2d").putImageData(context.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)
					  pdf.addImage(page.toDataURL("image/jpeg", 1.0), "JPEG", 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width)) // 添加图像到页面，保留10mm边距
			 
					  renderedHeight += imgHeight
					  if (renderedHeight < canvas.height) { pdf.addPage() }// 如果后面还有内容，添加一个空页
					  // delete page;
					}
					pdf.save('个人隐私载体销毁报告' + '.pdf')
					
					
				}).catch((r) => {
					console.log(r);
				})
			},
			// 下载视频
			downloadVideo(index,propName,isPlay=false){
				uni.showLoading({
					title:"视频加载中"
				})
				let that=this
				const urlKey = propName + 'Video';
				const pathKey = propName + 'VideoPath';
				let item= that.reportData.items[index]
				const url = item[urlKey]
				//const spindex = url.indexOf('/'); // 找到第一个斜杠的位置
				const bucketName = 'kiosk-destroy'//url.substring(0, spindex); // 获取前半部分  
				//const fileName = url.substring(spindex); // 
				// let param={
				// 	bucketName:bucketName,
				// 	fileName:fileName
				// }
				
				uni.downloadFile({
					url:"v1/oss/minio/download?bucketName="+bucketName+"&fileName="+url,
					success(res) {
						uni.hideLoading()
						if(res.statusCode === 200){
							that.reportData.items[index][pathKey]=res.tempFilePath
							if(isPlay){
								that.playVideo(index,propName)
								
								
							}else{
								that.getVideoThumb(index,propName)
							}
						}
					},
					fail() {
						uni.hideLoading()
						uni.showToast({
							title:"获取视频失败，请稍后再试"
						})
					}
				})
				
			},
			
			//从视频中截取封面
			getVideoThumb(index, propName) {
				const urlKey = propName + 'Video';  
				const pathKey = propName + 'VideoPath';
				 const picKey = propName + 'Pic';  
				let item = this.reportData.items[index]
				let itemUrl = item[urlKey]
				let url = item[pathKey]
				if(itemUrl){
					//判断视频是否已下载
					if(url){
						let dataURL = '';
						let myvideo = document.createElement("video");
						const videoFps={'place':1,'destory':200,'finish':250}
						myvideo.setAttribute('crossOrigin','anonymous');//处理跨域
						myvideo.setAttribute('src', url);
						myvideo.setAttribute('width', 640);
						myvideo.setAttribute('height', 368);
						myvideo.currentTime = videoFps[propName];
						myvideo.addEventListener('loadeddata', () => {
							let canvas = document.createElement("canvas")
							let width = myvideo.width //canvas的尺寸和图片一样
							let height = myvideo.height;
							canvas.width = width;
							canvas.height = height;
							canvas.getContext("2d").drawImage(myvideo, 0, 0, width, height); //绘制canvas
							dataURL = canvas.toDataURL('image/jpeg'); //转换为base64
							// console.log(dataURL)
							const picKey = propName + 'Pic';
							this.reportData.items[index][picKey] = dataURL;
						});
					}else{
						this.downloadVideo(index,propName)
					}
					
				}else{
					this.reportData.items[index][picKey] = "../../static/noimg.png"; 
				}
				
			},
			//播放视频
			playVideo(index,propName){
				const urlKey = propName + 'Video';
				const pathKey = propName + 'VideoPath';
				let item= this.reportData.items[index]
				let that = this
				//普通视频播放
				if(item[pathKey]!== ''){
					that.$refs.popup.open()
					that.videoConfig.autoplay=true
					setTimeout(()=>{
						if (that.jmuxer) {
						    that.jmuxer.destroy();
						}
						fetch(item[pathKey]).then(res => res.blob()).then(blob => {
							that.fileToBuf(blob)
						})
						that.jmuxer = new JMuxer({
							node: that.$refs.player,
							mode: 'video',
							flushingTime: 1000,
							fps: 30,
							clearBuffer: true,
							debug: false
						});
						// this.$refs.popup.open()
						
					},2000)
					// that.videoConfig.path=item[pathKey]
					
				}else{
					that.downloadVideo(index,propName,true)
				}
			},
			fileToBuf(file){
				let that =this
				let reader = new FileReader();
				console.log(file)
				reader.readAsArrayBuffer(file);
				reader.addEventListener("loadend",(e) => {
					that.jmuxer.feed({
						video: new Uint8Array(e.target.result),
						duration: 0
					});
				},false);
			
			},
			closwVideo(){
				this.$refs.popup.close()
				this.videoConfig.autoplay=false
			},
			previewImage(item,index){
				let picList=[item.placePic,item.destoryPic,item.finishPic]
				uni.previewImage({
					current:index,
					urls:picList,
					indicator:"default"
				})
			},
			showRTime(date){
				if(date){
					return moment(date).format('YYYY年MM月DD日 HH:mm:ss');
				}else{
					return "-"
				}
				
			},
			getFullDate (targetDate) {
			    let D, y, m, d;
			    if (targetDate) {
			        D = new Date(targetDate);
			        y = D.getFullYear();
			        m = D.getMonth() + 1;
			        d = D.getDate();
			    } else {
			        y = fullYear;
			        m = month;
			        d = date;
			    }
			    m = m > 9 ? m : '0' + m;
			    d = d > 9 ? d : '0' + d;
			    this.date= y + '年' + m + '月' + d+'日';
			},
			//获取图片
			processImage(item, index, propName) {  
			  const imgKey = propName + 'Img';  
			  const picKey = propName + 'Pic';  
			  if (item[imgKey]) { 
				 // const spindex = item[imgKey].indexOf('/'); // 找到第一个斜杠的位置  
				  const bucketName = 'kiosk-destroy'//item[imgKey].substring(0, spindex); // 获取前半部分  
				  const fileName = item[imgKey]//item[imgKey].substring(spindex); // 
				  // console.log(fileInfo)
				getImg({  
				  bucketName: bucketName,  
				  fileName: fileName,  
				}).then(res => {  
				  const base64Str = 'data:image/png;base64,' + res.data;  
				  this.reportData.items[index][picKey] = base64Str.replace(/[\r\n]/g, "");  
				}).catch(error => {  
				  console.error(`Error fetching ${picKey} image for item at index ${index}:`, error);  
				});  
			  } else { 
				  this.reportData.items[index][picKey] = "../../static/noimg.png"; 
				// this.getVideoThumb(index, propName)
			  }  
			},
			//分别获取各个过程的图片
		 	loadImg(){
				this.reportData.items.forEach((item, index) => {  
					this.processImage(item, index, 'place');  
					this.processImage(item, index, 'destory');  
					this.processImage(item, index, 'finish');  
				});
			},
			
			getData(){
				uni.showLoading()
				let param={
					orderId:this.id
				}
				getReport(param).then(res=>{
					
					uni.hideLoading()
					if(res.data){
						let reportData=res.data
						this.location=reportData.report.provider.name
						this.machineNo=reportData.report.provider.code
						this.businessNo=reportData.report.businessNo
						// 创建一个映射来存储图片信息  
						const imageMap = new Map();  
						// 创建一个映射来存储视频信息  
						const videoMap = new Map();  
						  
						// 遍历所有附件以创建映射  
						reportData.report.attachs.forEach(attach => {  
						  const { desc, path, attachType, ownerId } = attach;  
						  if (attachType === "IMAGE") {  
						    if (!imageMap.has(ownerId)) {  
						      imageMap.set(ownerId, {});  
						    }  
						    imageMap.get(ownerId)[desc] = path;
							 
						  } else if (attachType === "VIDEO") {  
						    if (!videoMap.has(ownerId)) {  
						      videoMap.set(ownerId, {});  
						    }
						    videoMap.get(ownerId)[desc] = path;  
						  }  
						});
						
						// console.log(imageMap)
						// console.log(videoMap)
						reportData.items.forEach(item => {  
						  if (item.state === "DONE") {  
							let mapKey=String(item.id)+'_'
						    const images = imageMap.get(String(item.id)) || {};  
						    const videos = videoMap.get(String(item.id)) || {}; 
							// if(!videos.place){
							// 	videos.place=videos[mapKey+1];
							// }
							// if(!videos.destory){
							// 	videos.destory=videos[mapKey+2];
							// }
							// if(!videos.finish){
							// 	videos.finish=videos[mapKey+3];
							// }
							// if(!images.place){
							// 	images.place=images[mapKey+1];
							// }
							// if(!images.destory){
							// 	images.destory=images[mapKey+2];
							// }
							// if(!images.finish){
							// 	images.finish=images[mapKey+3];
							// }
						    const info = {
								id: item.id,  
								name: item.name,  
								update: item.update,
								placeImg: images[mapKey+1] || '',  
								placePic: '',
								placeVideo: videos[mapKey+1] || '', 
								placeVideoPath:'',
								destoryImg: images[mapKey+2] || '',  
								destoryVideo: videos[mapKey+2] || '',  
								destoryVideoPath:'',
								destoryPic: '',   
								finishImg: images[mapKey+3]|| "",  
								finishVideo: videos[mapKey+3] || '',  
								finishVideoPath:'',
								finishPic: '' 
						    };  
						  // console.log(info)
						    this.reportData.items.push(info);  
						  }  
						});
						this.loadImg()
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	page{
		font-family: "宋体";
	}
	p{
		margin: 10px 2px;
	}
	.btn-con{
		display: none;
	}
	.header{
		width: 100%;
		.navLeft,.download-btn-box{
			
		}
		.navTitle{
			display: flex;
			justify-content: space-around;
			width: 100%;
			text-align: center;
		}
	}
	.btn-box{
		display: flex;
		margin: 10px 0;
		justify-content: flex-end;
		text-align: right;
		.download-btn{
			background-color: steelblue;
			color: white;
		}
	}
	.blode{
		font-weight: bold;
	}
	.title{
		margin: 25px 0 10px;
		font-family: "黑体";
	}
	.companyInfo{
		text-align: left;
		margin-top: 20px;
	}
	.container {
		padding: 20px;
		font-size: 14px;
		line-height: 24px;
	}
	.video-box{
		height: 100vh;
		display: flex;
		flex-direction: column;
		justify-content: center;
		background: #000;
		text-align: center;
		.close-btn{
			height: 30px;
			position: absolute;
			top: 10px;
			right: 10px;
		}
		.video{
			width: 100%; 
			height: calc(100% - 30px); 
			margin-top: 30px;
		}
	}
</style>
